<template>
  <div class="dashboard-editor-container">

    <!--<github-corner style="position: absolute; top: 0px; border: 0; right: 0;"/>-->

    <!--<div>-->
    <div class="tip">
      <p class="active_sm">活动抽奖规则说明: </p>

      <p class="sm-text">1、活动用户: 登录过小程序并同意授权用户后即视为 "活动用户"。</p>
      <p class="sm-text">2、礼券数: 活动初始的礼包数量是5000个，可以通过追加礼包按钮追加礼包数目每次追加礼包数应小于"1000"。</p>
      <p class="sm-text">3、活动金额是: 付费用户数 * 9.9 后舍去小数点的金额。最终收入以微信商户后台为准。</p>
      <p class="sm-text">4、抽奖奖品数量: 初始化20000个奖品（3份A5大奖、100份升级券、3770份100元体验券、5000份50元体验券、其余为20元体验券）</p>
    </div>

    <div>


      <panel-group @handleSetLineChartData="handleSetLineChartData"/>
      <el-row>

        <el-col :sapn="24">

          <label for="活动时间：">活动时间：{{ parseTime(startTime) }} - {{ parseTime(endTime) }}</label>

          <el-button size="mini"  type="primary" style="float: right;" @click="setActiveTime()">设置活动时间</el-button>
          <div class="block" style="margin-right: 20px; float: right;">
            <el-date-picker
              size="mini"
              v-model="activeTime"
              type="datetimerange"
              :picker-options="pickerOptions2"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="right">
            </el-date-picker>
          </div>

        </el-col>

      </el-row>


      <el-row style="margin-top: 16px;">
        <el-col :span="3">
          <label for="" style="position: relative; top: 10px;">追加活动礼券：</label>
        </el-col>

        <el-col :span="6">

          <el-input size="mini"   v-model="num1" placeholder="请输入内容"></el-input>

        </el-col>

        <el-col :span="2" style="margin-left: 8px;">
          <el-button size="mini"  type="primary"  @click="addTicket">追加体验券名额</el-button>
        </el-col>

      </el-row>



      <el-row style="margin-top: 16px;">
        <el-col :span="3">
          <label for="" style="position: relative; top: 10px;">追加奖品：</label>
        </el-col>

        <el-col :span="15">

          <el-select size="mini"  v-model="value" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
          <el-input size="mini"  style="width: 200px;"  v-model="num2" placeholder="请输入内容"></el-input>

          <el-button size="mini"  type="primary"  style="margin-left: 20px;"  @click="addPrize">追加奖品</el-button>

        </el-col>


      </el-row>

      <el-row>
        <el-col :sapn="10">
          <label for="奖池设置：">奖池设置：</label>


          <el-button size="mini"  type="primary" style="margin-top: 16px;margin-left: 40px;" @click="initPrize()">初始化奖池</el-button>

        </el-col>
      </el-row>


      <div style="margin-top: 16px;">

        <el-col :span="7">

          <el-input placeholder="微信昵称/手机号/姓名" @keyup.enter.native="searchUser" size="mini" v-model="keyword">
            <template slot="append">

              <el-button type="primary" @click="searchUser()"> 搜索</el-button>
            </template>
          </el-input>

        </el-col>

        <el-col :span="5" style="margin-left: 20px;">
          <el-radio-group v-model="payType" size="mini" @change="changeType">
            <el-radio-button label="全部" value="0"></el-radio-button>
            <el-radio-button label="已支付" value="1"></el-radio-button>
            <el-radio-button label="未支付" value="2"></el-radio-button>
          </el-radio-group>
        </el-col>

        <div class="download_xlxs" @click="exportTable()">下载用户信息xlxs</div>
      </div>



      <el-row style="margin-top: 40px;">

        <div style="margin-top: 20px;">
          <el-table
            :data="userData"
            ref="userData"
            style="width: 100%; margin-top: 10px; font-size: 13px;"
            :header-cell-style="{
    'background-color': '#fafafa',
    'color': 'rgb(35, 35, 35)',
    'border-bottom': '1px #409EFF solid'
}"
            :row-style = "{
        'color': '#696969',
        }"
          >
            <el-table-column
              fixed
              prop="id"
              label="用户ID"
              width="100">
            </el-table-column>
            <el-table-column
              prop="avatarUrl"
              label="用户头像"
              width="100">
              <template slot-scope="scope">
                <img class="list_item_img" :src="scope.row.avatarUrl" alt="">
              </template>
            </el-table-column>

            <el-table-column
              prop="nickName"
              label="微信昵称"
              width="120"
            >
            </el-table-column>

            <el-table-column
              prop="name"
              label="姓名"
              width="100"
            >
            </el-table-column>

            <el-table-column
              prop="phone"
              label="手机号"
              width="150">

            </el-table-column>


            <el-table-column
              prop="gender"
              label="性别	"
              width="100"
            >
              <template slot-scope="scope">
                <p>{{ scope.row.gender == 1 ? '男' : '女'}}</p>
              </template>
            </el-table-column>

            <el-table-column
              prop="count"
              label="剩余抽奖次数"
              width="150"
            >

            </el-table-column>

            <el-table-column
              prop="is_ticket"
              label="是否9.8元抢券用户"
              width="150"
            >
              <template slot-scope="scope">
                <!--<el-switch-->
                  <!--v-model="scope.row.is_ticket == 1 ? true : false"-->
                <!--&gt;-->
                <!--</el-switch>-->

                <div v-if="scope.row.is_ticket == 0" class="badge_dot1"></div>
                <span v-if="scope.row.is_ticket == 0" class="badge_dot_text">未支付</span>

                <div v-if="scope.row.is_ticket == 1" class="badge_dot2"></div>
                <span v-if="scope.row.is_ticket == 1" class="badge_dot_text">已支付</span>

              </template>

            </el-table-column>

            <el-table-column
              prop="count"
              label="用户注册时间"
              width="150"
            >
              <template slot-scope="scope">
                <p>{{ parseTime(scope.row.create_time) }}</p>
              </template>

            </el-table-column>


            <el-table-column label="操作">
              <template slot-scope="scope">

                <!--<el-button type="danger" @click="delTeamUser(scope.$index, scope.row)" round>移出团队</el-button>-->

              </template>
            </el-table-column>
          </el-table>


          <div class="m_pagination" style="margin-top: 10px;margin-bottom: 40px;">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10]"
              :page-size="10"
              layout="total, sizes, prev, pager, next, jumper"
              :total="userTotal">
            </el-pagination>
          </div>

        </div>


      </el-row>

      <el-row />


    </div>




  </div>
</template>

<script>
import GithubCorner from '@/components/GithubCorner'
import PanelGroup from './components/PanelGroup'
import LineChart from './components/LineChart'
import RaddarChart from './components/RaddarChart'
import PieChart from './components/PieChart'
import BarChart from './components/BarChart'
import TransactionTable from './components/TransactionTable'
import TodoList from './components/TodoList'
import BoxCard from './components/BoxCard'
import Cookies from 'js-cookie'
import t from './../../../utils/request'
import { parseTime } from './../../../utils/index'
import $ from 'jquery'

const lineChartData = {
  newVisitis: {
    expectedData: [0, 0, 34, 0, 0, 0, 0],
    actualData: [0, 0, 91, 0, 0, 0, 0]
  },
  messages: {
    expectedData: [200, 192, 120, 144, 160, 130, 140],
    actualData: [180, 160, 151, 106, 145, 150, 130]
  },
  purchases: {
    expectedData: [80, 100, 121, 104, 105, 90, 100],
    actualData: [120, 90, 100, 138, 142, 130, 130]
  },
  shoppings: {
    expectedData: [130, 140, 141, 142, 145, 150, 160],
    actualData: [120, 82, 91, 154, 162, 140, 130]
  }
}

export default {
  name: 'DashboardAdmin',
  components: {
    GithubCorner,
    PanelGroup,
    LineChart,
    RaddarChart,
    PieChart,
    BarChart,
    TransactionTable,
    TodoList,
    BoxCard,
  },
  data() {
    return {
      lineChartData: lineChartData.newVisitis,
      userInfo: 0,
      pickerOptions2: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      value4: [new Date(2000, 10, 10, 10, 10), new Date(2000, 10, 11, 10, 10)],
      activeTime: '',
      startTime: null,
      endTime: null,
      userData: null,
      currentPage: 1,
      userTotal: 0,
      options: [{
        value: '8',
        label: 'A5大奖'
      }, {
        value: '2',
        label: '100元抵购券'
      }, {
        value: '7',
        label: '50元抵购券'
      }, {
        value: '3',
        label: '20元抵购券'
      }],
      value: '',
      num1: '',
      num2: '',

      payType: '全部',
      currentType: 0,
      keyword: ''
    }
  },
  created() {
    // Cookies.set('sidebarStatus', 1)
    console.log(parseTime(1547024396), 999);
  },

  mounted() {
    this.changeType()
    t.toPost('/admin/active/time', {}, (res) => {
      console.log(this.timestampToTime(res.data.start_time))
      this.startTime = this.timestampToTime(res.data.start_time)
      this.endTime = this.timestampToTime(res.data.end_time)
    })

    t.toPost('/admin/user/list', {
      type: this.currentType
    }, (res) => {
      console.log(res)
      this.userData = this.UserList(res)
      this.userTotal = res.data.total
    })
  },
  methods: {
    handleSetLineChartData(type) {
      this.lineChartData = lineChartData[type]
    },

    parseTime(time) {
      return parseTime(time)
    },

    // 订单数据绑定
    UserList(data) {
      var UList = data.data.data
      var UserOptions = []
      for (var i = 0; i < UList.length; i++) {
        var option = UList[i]
        // 数据绑定
        UserOptions.push(option)
      }
      return UserOptions
    },

    setActiveTime() {
      if (!this.activeTime[0] || !this.activeTime[1]) {
        this.$message({
          showClose: true,
          message: '未设置活动时间',
          type: 'error'
        });
        return;
      }
      var startTime = new Date(this.activeTime[0]).getTime() / 1000
      var endTime = new Date(this.activeTime[1]).getTime() / 1000
      console.log(startTime, endTime)
      t.toPost('/admin/active/settime', {
        startTime: startTime,
        endTime: endTime
      }, (res) => {
        console.log(res, 66)
        if (res.code === '000000') {
          this.$message({
            showClose: true,
            message: '恭喜你，时间设置成功',
            type: 'success'
          });
        }
      })

    },

    timestampToTime(timestamp) {
      var date = new Date(timestamp * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var Y = date.getFullYear() + '-';
      var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
      var D = date.getDate() + ' ';
      var h = date.getHours() + ':';
      var m = date.getMinutes() + ':';
      var s = date.getSeconds();
      return Y+M+D+h+m+s;
    },
    initPrize() {
      this.$confirm('此操作会影响活动的公平性', '是否继续初始化奖池?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        t.toPost('/admin/active/init_prize', {}, ()=> {
          this.$message({
            type: 'success',
            message: '初始化成功!'
          });
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    handleSizeChange() {

    },

    handleCurrentChange(val) {
      t.toPost('/admin/user/list', {
        page: val,
        num: 10,
        type: this.currentType
      }, (res) => {
        this.userData = this.UserList(res)
        this.userTotal = res.data.total
      })
    },

    addTicket: function () {
      t.toPost('/admin/ticket/add', {
        num: this.num1
      }, (res) => {
        if (res.code == '000000') {
          this.$message({
            type: 'success',
            message: '体验名额增加成功!'
          });
          this.$router.go(0)
        }
      })
    },

    addPrize: function () {
      t.toPost('/admin/prize/add', {
        type: this.value,
        num: this.num2
      }, (res) => {
        if (res.code == '000000') {
          this.$message({
            type: 'success',
            message: '体验名额增加成功!'
          });
          this.$router.go(0)
        }
      })
    },

    exportTable() {

      var url = 'https://market.jackgroup.cn/index.php/admin/user/export';
      var form=$("<form>");//定义一个form表单
      form.attr("style","display:none");
      form.attr("target","");
      form.attr("method","post");//请求类型
      form.attr("action",url);//请求地址
      $("body").append(form);//将表单放置在web中

      form.submit();//表单提交
    },

    //
    changeType() {
      console.log(this.payType, 88)
      if (this.payType == '全部') {
        this.currentType = 0
      }
      if (this.payType == '已支付') {
        this.currentType = 1
      }
      if (this.payType == '未支付') {
        this.currentType = 2
      }

      t.toPost('/admin/user/list', {
        page: 1,
        num: 10,
        type: this.currentType
      }, (res) => {
        this.userData = this.UserList(res)
        this.userTotal = res.data.total
      })
    },

    searchUser() {
      // if (!this.keyword) {
      //   this.$message({
      //     type: 'error',
      //     message: '请输入查询内容!'
      //   });
      //   return;
      // }
      t.toPost('/admin/user/list', {
        type: this.currentType,
        keyword: this.keyword
      }, (res) => {
        console.log(res)
        this.userData = this.UserList(res)
        this.userTotal = res.data.total
      })
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.dashboard-editor-container {
  padding: 32px;
  background-color: #f1f4f5;
  .chart-wrapper {
    background: #fff;
    padding: 16px 16px 0;
    margin-bottom: 32px;
  }
}

  .content_main {
    position: relative;
    width: 100%;
    min-height: 700px;
    background-color: #f1f4f5;
  }

  .list_item_img {
    position: relative;
    width: 40px;
    height: 40px;
    border-radius: 5px;
  }

  label {
    position: relative;
    font-size: 14px;
    font-weight: 600;
    color: #323232;
  }

 .tip {
  padding: 8px 16px;
  background-color: #ecf8ff;
  border-radius: 4px;
  border-left: 5px solid #50bfff;
}

  .active_sm {
    position: relative;
    color: #333333;
    font-weight: 600;
  }

  .sm-text {
    font-size: 14px;
    color: #686868;
  }

  .badge_dot1 {
    display: inline-block;
    position: relative;
    width: 6px;
    height: 6px;
    border-radius: 50%;
    vertical-align: middle;
    background-color: #f5222d;
  }

  .badge_dot2 {
    display: inline-block;
    position: relative;
    width: 6px;
    height: 6px;
    border-radius: 50%;
    vertical-align: middle;
    background-color: #409EFF;
  }

  .badge_dot_text {
    color: #686868;
    margin-left: 10px;
  }
  .download_xlxs {
    float: right;
    text-align: right;
    font-size:14px;
    color: #409eff;
    margin-top:10px;
  }
  .download_xlxs:hover {
    border-bottom: 1px solid #409eff;
    cursor: pointer;
  }
</style>
